<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams" size="small">
        <el-form-item prop="params.loginName">
          <el-input
            v-model="queryParams.params.loginName"
            class="filter-item"
            clearable
            placeholder="账户名称"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item prop="params.showName">
          <el-input
            v-model="queryParams.params.showName"
            class="filter-item"
            clearable
            placeholder="真实名称"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item prop="params.phone">
          <el-input
            v-model="queryParams.params.phone"
            class="filter-item"
            clearable
            placeholder="电话"
            style="width: 150px;"
          />
        </el-form-item>
        <!-- <el-form-item prop="params.unitId">
          <el-cascader ref="unit-tree-ref" v-model="queryParams.params.unitId" :options="unitTreeData" :props="{emitPath: false, checkStrictly: true, expandTrigger: 'hover', value: 'id', label: 'name' }" :show-all-levels="false" @change="handleUnitChange" />
        </el-form-item> -->
        <!-- 按钮 -->
        <el-button
          v-permission="['/sys/user/search']"
          v-waves
          class="filter-item"
          icon="el-icon-search"
          size="small"
          style="margin-left: 10px;"
          type="primary"
          @click="getDataList"
        >查询
        </el-button>
        <el-button
          v-permission="['/sys/user/add']"
          v-waves
          class="filter-item"
          icon="el-icon-plus"
          size="small"
          type="primary"
          @click="handleOpenDialog('add')"
        >新增
        </el-button>
        <el-button
          v-permission="['/sys/user/search']"
          v-waves
          class="filter-item"
          icon="el-icon-refresh"
          size="small"
          type="primary"
          @click="resetQueryForm"
        >重置
        </el-button>
      </el-form>
    </div>
    <div class="table-container">
      <el-table
        v-loading="dataLoading"
        :data="dataList"
        border
        element-loading-text="拼命加载中"
        fit
        highlight-current-row
        size="small"
        style="width: 100%;"
        @sort-change="handleSortChange"
      >
        <el-table-column :index="shownIndex" align="center" fixed label="序号" type="index" />
        <el-table-column align="center" label="账户名称" prop="loginName" />
        <el-table-column align="center" label="真实姓名" prop="showName" />
        <el-table-column align="center" label="电话" prop="phone" sortable="custom" />
        <el-table-column align="center" label="邮箱" prop="email" />
        <el-table-column align="center" label="上次登录" prop="loginTime" sortable="custom" />
        <el-table-column :show-overflow-tooltip="true" align="center" label="备注" prop="remark" />
        <el-table-column align="center" label="操作" width="350">
          <template slot-scope="scope">
            <el-button
              v-permission="['/sys/user/update']"
              v-waves
              size="mini"
              type="primary"
              @click="handleOpenDialog('update', scope.row)"
            >编辑
            </el-button>
            <el-tooltip content="角色分配" placement="top">
              <el-button
                v-permission="['/sys/user/role']"
                v-waves
                size="mini"
                type="warning"
                @click="handleOpenDialog('rolesAssign', scope.row)"
              >角色
              </el-button>
            </el-tooltip>
            <el-tooltip content="密码重置" placement="top">
              <el-button
                v-permission="['/sys/user/reset-password']"
                v-waves
                size="mini"
                type="warning"
                @click="handleChangePassword(scope.row)"
              >重置
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除该用户" placement="top">
              <el-button
                v-permission="['/sys/user/delete']"
                v-waves
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.size"
        :page-sizes="[10,20,30, 50]"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增-编辑对话框 -->
    <el-dialog
      v-loading="dialogLoading"
      :close-on-click-modal="false"
      :title="dialogTitleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      element-loading-text="保存中"
      width="550px"
    >
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="rules"
        label-position="right"
        label-width="150px"
        size="small"
        style="width: 80%;"
      >
        <el-form-item label="账户名称：" prop="loginName">
          <el-input v-model="dataForm.loginName" placeholder="登录名称" />
        </el-form-item>
        <el-form-item label="真实姓名：" prop="showName">
          <el-input v-model="dataForm.showName" placeholder="真实姓名" />
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="dataForm.email" placeholder="邮箱" />
        </el-form-item>
        <el-form-item label="电话：" prop="phone">
          <el-input v-model="dataForm.phone" placeholder="电话" />
        </el-form-item>
        <el-form-item v-if="dialogStatus==='add'" label="密码：" prop="password">
          <el-input v-model="dataForm.password" placeholder="密码" />
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="dataForm.remark" placeholder="备注信息" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus==='add'" size="small" type="primary" @click="handleAdd">确定</el-button>
        <el-button v-else size="small" type="primary" @click="handleUpdate">确定</el-button>
      </div>
    </el-dialog>
    <!-- 角色分配对话框 -->
    <el-dialog
      v-loading="dialogLoading"
      :close-on-click-modal="false"
      :title="dialogTitleMap[dialogStatus]"
      :visible.sync="dialogRolesAssignVisible"
      element-loading-text="保存中"
      width="800px"
    >
      <div class="transfer-title">{{ currentRow ? currentRow.loginName : '' }}</div>
      <div class="transfer-wrapper">
        <el-transfer
          v-model="hasRoleList"
          :data="allRoleList"
          :filter-method="filterByRoleName"
          :titles="['未选', '已选']"
          filter-placeholder="请输入角色名称"
          filterable
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogRolesAssignVisible = false">取消</el-button>
        <el-button size="small" type="primary" @click="handleSaveRoleAssign">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { add, del, fetchList, getAssignedRoleList, resetPassword, saveRolesAssign, update } from '@/api/system/user'
import { fetchList as fetchRoleList } from '@/api/system/role'

export default {
  name: 'User',
  data() {
    return {
      dataLoading: false,
      dialogLoading: false,
      dialogFormVisible: false,
      dialogRolesAssignVisible: false,
      dialogStatus: '',
      total: 0,
      currentRow: null, // 当前操作行的数据
      dialogTitleMap: {
        add: '新增',
        update: '编辑',
        rolesAssign: '角色分配'
      },
      queryParams: {
        page: 1,
        size: 20,
        sortOrder: 'desc',
        sortName: 'id',
        params: {
          loginName: '',
          phone: '',
          showName: '',
          stationId: ''
        }
      },
      dataList: [],
      stationList: [],
      stationObject: {},
      allRoleList: [], // 所有角色列表
      hasRoleList: [], // 已有角色列表
      rules: {
        loginName: [{ required: true, message: '账户名称不能为空', trigger: 'change' }],
        showName: [{ required: true, message: '真实姓名不能为空', trigger: 'change' }],
        email: [{ required: true, message: '邮箱不能为空', trigger: 'change' }],
        phone: [{ required: true, message: '电话不能为空', trigger: 'change' }]
      },
      dataForm: {
        stationId: '',
        stationLimit: '',
        loginName: '',
        showName: '',
        email: '',
        phone: '',
        password: '',
        remark: '',
        accountType: 'all'
      },
      unitTreeData: []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      const ininDataFunc = async() => {
        this.getDataList()
      }
      ininDataFunc()
    },
    shownIndex(index) {
      return (this.queryParams.page - 1) * this.queryParams.size + index + 1
    },
    handleSizeChange(size) {
      this.queryParams.size = size
      this.getDataList()
    },
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.getDataList()
    },
    handleSortChange(data) {
      console.log('handleSortChange')
      console.log(data)
      if (data.order) {
        if (data.order.indexOf('asc') > -1) {
          this.queryParams.sortOrder = 'asc'
        } else {
          this.queryParams.sortOrder = 'desc'
        }
        this.queryParams.sortName = data.prop
      }
      console.log(this.queryParams)
      this.getDataList()
    },
    getDataList() {
      this.dataLoading = true
      fetchList(this.queryParams)
        .then(res => {
          console.log(res)
          this.dataList = res.data.records
          this.total = res.data.total
          this.dataLoading = false
        })
        .catch(err => {
          console.log(err)
          this.dataLoading = false
        })
    },
    getRoleDataList() {
      fetchRoleList({ size: 99, sortName: 'role_name', sortOrder: 'asc', params: {}})
        .then(res => {
          console.log(res)
          var roleList = res.data.records
          roleList.forEach((value, index, array) => {
            this.allRoleList.push({ key: value.id, label: value.roleName })
          })
        })
        .catch(err => {
          console.log(err)
        })
    },
    resetQueryForm() {
      this.$refs['queryForm'].resetFields()
      this.queryParams.page = 1
      this.queryParams.params.unitCodeLink = ''
      this.getDataList()
    },
    handleDelete(rowData) {
      this.$confirm('是否删除该用户？', '删除提示', { type: 'warning' })
        .then(() => {
          del(rowData.id)
            .then(res => {
              console.log(res)
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(cancel => {
          console.log(cancel)
        })
    },
    handleAdd() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          console.log(this.dataForm)
          this.dialogLoading = true
          add(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '新增用户成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleUpdate() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          update(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '修改用户成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleOpenDialog(type, rowData) {
      // 表单状态为新增/编辑、打开新增/编辑窗口
      this.resetDataForm()
      this.dialogStatus = type
      if (rowData) {
        this.currentRow = rowData
      }
      if (type === 'update') {
        this.dataForm = JSON.parse(JSON.stringify(rowData))
        this.dialogFormVisible = true
      } else if (type === 'add') {
        this.dialogFormVisible = true
      } else if (type === 'rolesAssign') {
        this.allRoleList = []
        this.hasRoleList = []
        // 获取所有的角色列表
        this.getRoleDataList()
        // 获取已分配的角色列表
        getAssignedRoleList({
          size: 99,
          params: { userId: this.currentRow.id }
        })
          .then(res => {
            console.log(res)
            var dataList = res.data.records
            dataList.forEach((value, index, array) => {
              this.hasRoleList.push(value.roleId)
            })
          })
          .catch(err => {
            console.log(err)
          })
        this.dialogRolesAssignVisible = true
      }
    },
    // 手动重置表单
    resetDataForm() {
      if (this.$refs['dataForm']) {
        // 由于编辑数据的时候会导致表单对象的初始化值发生变更，所以在重置表单前先手动重置表单对象的值
        this.dataForm = {
          stationId: '',
          stationLimit: '',
          loginName: '',
          showName: '',
          email: '',
          phone: '',
          remark: '',
          accountType: 'all'
        }
        this.$refs['dataForm'].resetFields()
      }
    },
    filterByRoleName(query, item) {
      console.log(item)
      return item.label.indexOf(query) > -1
    },
    handleSaveRoleAssign() {
      var itemList = []
      this.hasRoleList.forEach((value, index, array) => {
        itemList.push({ userId: this.currentRow.id, roleId: value })
      })
      // 当角色为空的时候，传一个空的用户id给后台
      if (itemList.length === 0) {
        itemList.push({ userId: this.currentRow.id, roleId: '' })
      }
      saveRolesAssign(itemList)
        .then(res => {
          console.log(res)
          this.dialogRolesAssignVisible = false
          this.$message.success(res.msg || '角色分配成功')
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleChangePassword(rowData) {
      this.$confirm('是否确认重置密码？', '提示', { type: 'warning' }).then(() => {
        resetPassword({ id: rowData.id }).then(res => {
          this.$message.success('密码重置成功！')
        })
      })
    },
    handleUnitChange(value) {
      var nodes = this.$refs['unit-tree-ref'].getCheckedNodes()
      if (nodes && nodes.length > 0) {
        this.queryParams.params.unitCodeLink = nodes[0].data.codeLink
      }
      var nodes2 = this.$refs['unit-tree-ref2'].getCheckedNodes()
      if (nodes2 && nodes2.length > 0) {
        this.dataForm.unitCodeLink = nodes2[0].data.codeLink
      }
    }
  }
}
</script>
<style scoped>
.el-form .el-select {
  width: 100%;
}

.transfer-wrapper {
  display: flex;
  justify-content: center;
}

.transfer-title {
  text-align: center;
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 30px;
}

.el-form .el-cascader {
  width: 100%;
}
</style>
